package com.springboot.exception;

import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.springboot.constant.ErrorCodeConstants;
import com.springboot.pojo.ResponsePojo;

@ControllerAdvice
public class GlobalExceptionHandler {

	@ExceptionHandler(value = { Exception.class })
	@ResponseBody
	public ResponsePojo<JSONObject> defaultErrorHandler(HttpServletRequest request, Exception e) throws Exception {
		ResponsePojo<JSONObject> resPojo = new ResponsePojo<JSONObject>();
		resPojo.setCode(ErrorCodeConstants.ERROR_500);
		resPojo.setDesc(e.getMessage());
		JSONObject body = new JSONObject();
		body.put("requestURI", request.getRequestURI());
		body.put("exception", getStackTrace(e));
		resPojo.setBody(body);
		return resPojo;
	}

	private String getStackTrace(Throwable t) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		try {
			t.printStackTrace(pw);
			return sw.toString();
		} finally {
			pw.close();
		}
	}

}
